package logic

import (
	"errors"
	"go.uber.org/zap"
	"strconv"
	"study-plan/common/dao"
	"study-plan/common/proto/study"
	"study-plan/service/pkg"
	"study-plan/service/utils"
)

// todo:用户注册
func UserRegister(in *study.UserRegisterRequest) (*study.UserRegisterResponse, error) {
	user, err := dao.GetUserInfo(in.UserName)
	if user != nil {
		zap.L().Error("user_register", zap.Error(err))
		return nil, errors.New("用户已存在")
	}
	if in.Password != in.NewPassword {
		zap.L().Error("user_register", zap.String("password", "二次密码不一致"))
		return nil, errors.New("二次密码不一致")
	}

	create, err := dao.UserCreate(in.UserName, utils.Md5(in.NewPassword))
	if err != nil {
		return nil, err
	}

	return &study.UserRegisterResponse{UserId: int64(create.ID)}, nil
}

// todo:用户登录
func UserLogin(in *study.UserLoginRequest) (*study.UserLoginResponse, error) {
	user, err := dao.GetUserInfo(in.UserName)
	if user == nil {
		zap.L().Error("user_login", zap.Error(err))
		return nil, errors.New("用户不存在")
	}
	if user.Password != utils.Md5(in.Password) {
		return nil, errors.New("密码错误,请重新输入")
	}

	return &study.UserLoginResponse{UserId: int64(user.ID)}, nil
}

// todo:购物车查询
func CarList(in *study.CarListRequest) (*study.CarListResponse, error) {
	list, err := dao.GetCatList(in.UserId)
	if err != nil {
		return nil, err
	}
	return &study.CarListResponse{List: list}, nil
}

// todo:购物车添加
func CarCreate(in *study.CarCreateRequest) (*study.CarCreateResponse, error) {

	course, err := dao.GetCourse(in.CourseId)
	if err != nil {
		return nil, errors.New("课程信息查询失败")
	}
	create, err := dao.UserCarCreate(in.UserId, course)
	if err != nil {
		return nil, errors.New("添加购物车失败")
	}
	return &study.CarCreateResponse{CourseId: create}, nil
}

// todo:购物车移除课程
func CarDelCourse(in *study.CarDelCourseRequest) (*study.CarDelCourseResponse, error) {

	err := dao.UserCarDelCourse(in.UserId, in.CourseId)
	if err != nil {
		return nil, errors.New("购物车移除课程失败")
	}

	return &study.CarDelCourseResponse{Success: true}, nil
}

// todo:订单创建
func OrderCreate(in *study.OrderCreateRequest) (*study.OrderCreateResponse, error) {

	course, err := dao.GetCourse(in.CourseId)
	if course == nil {
		return nil, errors.New("课程信息查询失败")
	}
	car, err := dao.GetUserCar(in.UserId)
	if err != nil {
		return nil, errors.New("购物车信息查询失败")
	}
	order, err := dao.OrderCreate(in, car.CoursePrice, car.CourseTitle, car.CarPrice)
	if err != nil {
		return nil, err
	}
	price := strconv.FormatFloat(order.OrderPrice, 'f', -1, 64)
	url := pkg.AliPay(car.CourseTitle, order.OrderSn, price)

	return &study.OrderCreateResponse{
		OrderId: int64(order.ID),
		Url:     url,
	}, nil
}
